package com.momoauth.api_client.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.momoauth.api_client.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {

    /**
     * 盐值
     * @param username
     * @return
     */
    @Select("SELECT salt FROM `user` WHERE username = #{username}")
    String getUserSalt(String username);

    /**
     * 密码
     * @param username
     * @return
     */
    @Select("SELECT `password` FROM `user` WHERE username = #{username}")
    String getUserPassword(String username);

    /**
     * 用户ID
     * @param username
     * @return
     */
    @Select("SELECT userId FROM `user` WHERE username = #{username}")
    Long getUserId(String username);

    /**
     * 判断是否存在有效用户
     * @param username
     * @return
     */
    @Select("SELECT 1 FROM `user` WHERE username = #{username} AND status = 1 AND isDelete = 0 LIMIT 1")
    Integer existValidUser(String username);

    /**
     * 查询是否存在同名用户
     * @param username
     * @return
     */
    @Select("SELECT 1 FROM `user` WHERE username = #{username} AND isDelete = 0 LIMIT 1")
    Integer existUserOfSameName(String username);

    /**
     * 查询用户列表
     * @param page
     * @param wrapper
     * @return
     */
    @Select("SELECT userId,username,realName,status,createTime FROM `user` ${ew.customSqlSegment}")
    List<User> getUserList(Page<User> page, @Param(Constants.WRAPPER) QueryWrapper wrapper);

    /**
     * 删除用户
     * @param user
     * @return
     */
    @Update("UPDATE `user` SET isDelete = 1 WHERE userId = #{userId}")
    Integer deleteUserById(User user);

    /**
     * 用户详情
     * @param userId
     * @return
     */
    @Select("SELECT userId,username,realName,dept_id,deptName,user.status " +
            "FROM `user` " +
            "LEFT JOIN department ON deptId = dept_id " +
            "WHERE userId = #{userId}")
    User getUserById(Long userId);

    /**
     * 修改密码
     * @param user
     * @return
     */
    @Update("UPDATE `user` SET password = #{password} WHERE userId = #{userId}")
    Integer changePassword(User user);

    /**
     * 查询是否有使用该部门的用户
     * @param dept_id
     * @return
     */
    @Select("SELECT 1 FROM `user` WHERE dept_id = #{dept_id} AND isDelete = 0 LIMIT 1")
    Integer existUserUseDepartmentById(Long dept_id);
}
